package com.lib.ui.activity.web.base;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;

import com.alibaba.android.arouter.launcher.ARouter;
import com.lib.app.ARouterPathUtils;
import com.lib.app.EventBusTagUtils;
import com.lib.bean.Event;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.permission.custom.PermissionUtil;
import com.lib.ui.activity.BaseWebActivity;
import com.lib.utls.live.ToClassUtils;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.simple.eventbus.Subscriber;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

public abstract class BaseBusinessWebActivity extends BaseWebActivity {

    //修改支付密码
    public static final int SET_PASSWORD = 1;

    //需要返回给H5的对象，通过EventBus获取值
    private String shareStr;

    public String token = "";

    private WebView myWebView;

    @Override
    protected void onCreateView(WebView webView) {

        //app加载webview，可以通过chrome调试    谷歌浏览器翻墙并访问chrome://inspect-->inspect
//        DWebView.setWebContentsDebuggingEnabled(true);
//        webView.setWebContentsDebuggingEnabled(true);

        this.myWebView = webView;

        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setSupportZoom(true);

        myWebView.addJavascriptInterface(javaScriptFunction, "AndroidInterface");
        myWebView.setWebViewClient(client);

        myWebView.setFocusableInTouchMode(true);
        myWebView.setFocusable(true);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            myWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

    }

    @Override
    protected int getLayoutId() {
        return getWebLayoutId();
    }


    protected abstract int getWebLayoutId();


    protected abstract void myOnPageStarted(WebView webView, String s, Bitmap bitmap);

    protected abstract void myShouldOverrideUrlLoading(WebView webView, String url);

    protected abstract void myOnPageFinished(WebView webView, String s);

    private WebViewClient client = new WebViewClient() {


        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);
            myOnPageStarted(webView, s, bitmap);

        }

        /**
         * 防止加载网页时调起系统浏览器
         */
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {

            LogUtil.e(url);

            //网页调用打电话时操作
            if (url.startsWith("tel:")) {

                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            } else {
                webView.loadUrl(url);

                myShouldOverrideUrlLoading(webView, url);
            }

            return true;
        }


        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);

//            webView.loadUrl("javascript:hideheader()");
            myOnPageFinished(webView, url);

        }
    };


    //------------------------------------------------------------------------------------JS交互

    /**
     * JS交互接口
     */
    public interface JavaScriptFunction {
        //登录
        void appPushLogin();

        //获取Token
        String appGetToken();

        //充值
        void appPushRecharge(String userToken);

        //修改支付密码
        void appPushSetPayPass(String userToken);

        //进入直播间2
        void appPushLiveRoomV2(String course_type, String course_id);

        //隐藏当前WebView
        void appHiddenController();

        //分享到分享圈或第三方
        void appShowShareView(String business_obj);

        //跳转到我的课程界面
        void appPushMyCourseView();

        //从收藏列表跳转到视频详情界面
        void appPushGoodCourseInfo(String video_id);

        //跳转到收藏列表界面
        void appPushLikeGoodCourseList();

        //调用支付
        void appPushBuyGoodCourse(String productId);

        //展示1元领取弹出框
        void appPushGetFreeVip(String pass_id, String user_name, String user_icon, String user_days);

        //2020-2-17新增接口，用于打开微信
        void appPushWechat();

        //2020-2-19新增接口，用于关闭webview
        void appCloseWebView(String userToken);

        //2020-4-14新增接口，用于跳转1对1支付界面
        void appPushOtoPayView(String payId);

    }


    private JavaScriptFunction javaScriptFunction = new JavaScriptFunction() {
        @JavascriptInterface // 加上注解 getUrl() 方法才能被 JS 调用
        public void appPushLogin() {
            ARouter.getInstance().build(ARouterPathUtils.User_LoginActivity).navigation();

        }


        @JavascriptInterface
        public String appGetToken() {

            return token;
        }

        @JavascriptInterface
        public void appPushRecharge(String userToken) {

            if (checkToken(userToken)) return;

            ARouter.getInstance().build(ARouterPathUtils.User_RechargeActivity).navigation();

        }

        @JavascriptInterface
        public void appPushSetPayPass(String userToken) {
            if (checkToken(userToken)) return;

            ARouter.getInstance().build(ARouterPathUtils.User_SetZhiFuActivity)
                    .withInt("NOW_TYPE", SET_PASSWORD)
                    .navigation();
        }


        @JavascriptInterface
        public void appPushLiveRoomV2(String course_type, String course_id) {

            ToClassUtils.getInstance(BaseBusinessWebActivity.this).goToClass(course_type, course_id);

        }

        @JavascriptInterface
        public void appHiddenController() {

            finish();

        }

        @JavascriptInterface
        public void appShowShareView(String business_obj) {
            toShare1(business_obj);
        }


        @JavascriptInterface
        public void appPushMyCourseView() {

            LogUtil.e("网页调用接口，进入课程列表");

            ARouter.getInstance().build(ARouterPathUtils.User_MyClassActivity).navigation();

        }

        @JavascriptInterface
        public void appPushGoodCourseInfo(String video_id) {

            LogUtil.e("=======================>点击了appPushGoodCourseInfo");

            ARouter.getInstance().build(ARouterPathUtils.YouXuan_ClassDetailActivity)
                    .withString("video_id", video_id).navigation();

        }

        @JavascriptInterface
        public void appPushLikeGoodCourseList() {
            LogUtil.e("=======================>appPushLikeGoodCourseList");

            ARouter.getInstance().build(ARouterPathUtils.YouXuan_CourseCollectListActivity)
                    .navigation();
        }

        @JavascriptInterface
        public void appPushBuyGoodCourse(String productId) {

            LogUtil.e("=======================>appPushBuyGoodCourse");
            //productId的值（xstvip48  xstvip68）

        }

        @JavascriptInterface
        public void appPushGetFreeVip(String pass_id, String user_name, String user_icon, String user_days) {

            LogUtil.e("=======================>appPushGetFreeVip");
            LogUtil.e("pass_id=" + pass_id + "，user_name=" + user_name + "，user_icon=" + user_icon + "，user_days=" + user_days);
            //获取临时的vip体验卡  pass_id邀请人口令Id  user_name邀请人姓名  user_icon邀请人头像  user_days赠送的天数
            if (!"".equals(pass_id) && !"".equals(user_name) && !"".equals(user_icon) && !"".equals(user_days)) {

            } else {
                LogUtil.e("=======================>appPushGetFreeVip有参数为空");
            }

        }

        @JavascriptInterface
        public void appPushWechat() {

            //先根据地址获取图片，再保存到本地
            String imgUrl = "http://cdn.xuesituedu.com/gongzhonghao@3x.png";

            new ImageTask().execute(imgUrl);

            getWechatApi();
        }

        @JavascriptInterface
        public void appCloseWebView(String userToken) {
            finish();
        }


        @JavascriptInterface
        public void appPushOtoPayView(String payId) {//该订单的Id

            ARouter.getInstance().build(ARouterPathUtils.User_OtoRechargeActivity)
                    .withString("payId", payId).navigation();

        }

    };


    class ImageTask extends AsyncTask<String, Void, Bitmap> {

        protected Bitmap doInBackground(String... strings) {
            URL imageUrl = null;
            Bitmap bitmap = null;
            InputStream inputStream = null;
            try {
                imageUrl = new URL(strings[0]);
                HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                inputStream = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                saveImage(bitmap);
            }
        }
    }

    private void saveImage(Bitmap image) {
        String saveImagePath = null;
        Random random = new Random();
        String imageFileName = "xuesituerweima.jpg";
        File storageDir = new File(Environment.getExternalStoragePublicDirectory
                (Environment.DIRECTORY_PICTURES) + "xuesitu");

        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
        }
        if (success) {
            File imageFile = new File(storageDir, imageFileName);
            saveImagePath = imageFile.getAbsolutePath();
            try {
                OutputStream fout = new FileOutputStream(imageFile);
                image.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Add the image to the system gallery
            //将图片保存到相册中
            galleryAddPic(saveImagePath);
//            showToast("图片保存成功");
        }
    }

    /**
     * @param imagePath //将图片保存到相册中
     */
    private void galleryAddPic(String imagePath) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(imagePath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        sendBroadcast(mediaScanIntent);
    }


    /**
     * 跳转到微信
     */
    private void getWechatApi() {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            // TODO: handle exception
            showToast("检查到您手机没有安装微信，请安装后使用该功能");
        }
    }


    private void toRoom(final String roomToken, final String teacherPhone, final String roomName) {
        PermissionUtil.getInstance(BaseBusinessWebActivity.this).externalZhiBo(new PermissionUtil.RequestPermission() {
            @Override
            public void onRequestPermissionSuccess() {

                ARouter.getInstance().build(ARouterPathUtils.Live_MainRoomActivity)
                        .withString("roomToken", roomToken)
                        .withString("teacherPhone", teacherPhone)
                        .withString("roomName", roomName)
                        .navigation();
            }

            @Override
            public void onRequestPermissionFailure() {

            }

        });
    }

    private boolean checkToken(String userToken) {
        if (!token.equals(userToken)) {

            ARouter.getInstance().build(ARouterPathUtils.User_LoginActivity).navigation();

            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

        if ("".equals(myWebView.getUrl()) || null == myWebView.getUrl()) {

            return;

        } else {

            String webviewUrl = myWebView.getUrl();

            LogUtil.e("当前webview的地址为：" + webviewUrl);

            if (webviewUrl.contains("teacherHome")) {

                LogUtil.e("当前webview页面在老师空间,不用刷新界面");

                token = SharedPreferenceManager.getInstance(getApplicationContext()).getUserCache().getUserToken();


            } else {
                if (myWebView != null) {
                    token = SharedPreferenceManager.getInstance(getApplicationContext()).getUserCache().getUserToken();

                    myWebView.loadUrl("javascript:appOrderRefresh()");

                }
            }

        }

    }

    /**
     * 获取回调结果
     *
     * @param event
     */
    @Subscriber(tag = EventBusTagUtils.SendDateToH5)
    public void fromShareCallback(Event event) {

        LogUtil.e("传递过来的EventCode()：" + event.getEventCode() + "，json字符串为：" + event.getData());

        switch (event.getEventCode()) {

            case 1:

                //app分享回调,获得优惠劵
                if (myWebView != null) {

                    LogUtil.e("shareStr的值为：" + event.getData() + ",开始加载h5的方法");
                    myWebView.loadUrl("javascript:appCallbackCoupon('" + event.getData() + "')");
                }

                break;
        }
    }


    //---------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------分享
    //---------------------------------------------------------------------------------------------

    //需要分享到分享圈的
    private String htmlShare[] = {
            "curriculum_accompany.html",
            "curriculum_many.html",
            "article_content.html",
            "assistant/assistant_message.html",
            "videocourse/videocourse_message.html",
            "personal/teacherHome.html",
            "personal/teacherHome_topic.html"
    };

    private boolean isShareCircle = false;

    /**
     * 分享
     */
    public void toShare() {

        if ("".equals(myWebView.getUrl()) || null == myWebView.getUrl()) {

            return;
        } else {

            final String url = myWebView.getUrl();

            showLog("分享连接检测" + url);

            for (String s : htmlShare) {

                if (url.contains(s)) {
                    isShareCircle = true;
                }

            }

            if (isShareCircle) {


            } else {

            }

//            if (url.contains("article_content.html")) {//如果当前为文章界面，可以分享文章获得2元现金
//
//                HttpUtils.with(this)
//                        .addParam("requestType", "FISSION_NEW_USER")
//                        .addParam("url", url)
//                        .addParam("token", token)
//                        .execute(new HttpNormalCallBack<UserShareGetMoneyBean>() {
//                            @Override
//                            public void onSuccess(UserShareGetMoneyBean result) {
//
//                                if (CodeUtil.CODE_200 == result.getCode()) {
//
//                                    LogUtil.e("isShow的值为：" + result.getObj().getIs_show() +
//                                            ",isShareCircle的值为：" + isShareCircle);
//
//                                    if (1 == result.getObj().getIs_show()) {
//
//                                        if (isShareCircle) {
//
//                                            ShareUtils.getInstance(BaseBusinessWebActivity.this)
//                                                    .setShareParams(ShareUtils.SHARE_TYPE0, url)
//                                                    .hideCircle(false)
////                                                    .showMoney(true)
//                                                    .onPenCoustomShareBorad();
//
//                                        } else {
//
//                                            ShareUtils.getInstance(BaseBusinessWebActivity.this)
//                                                    .setShareParams(ShareUtils.SHARE_TYPE1, url)
//                                                    .hideCircle(true)
////                                                    .showMoney(true)
//                                                    .onPenCoustomShareBorad();
//                                        }
//
//                                    } else {
//
//                                        if (isShareCircle) {
//
//                                            ShareUtils.getInstance(BaseBusinessWebActivity.this)
//                                                    .setShareParams(ShareUtils.SHARE_TYPE0, url)
//                                                    .hideCircle(false)
//                                                    .onPenCoustomShareBorad();
//
//                                        } else {
//
//                                            ShareUtils.getInstance(BaseBusinessWebActivity.this)
//                                                    .setShareParams(ShareUtils.SHARE_TYPE1, url)
//                                                    .hideCircle(true)
//                                                    .onPenCoustomShareBorad();
//                                        }
//
//
//                                    }
//                                }
//
//                            }
//
//                            @Override
//                            public void onError(String e) {
//
//                            }
//                        });
//
//
//            } else {
//
//            }

        }

    }


    public void toShare1(String business_obj) {

        showLog("网页开始调用分享方法。。。。。。。。。。。。。。。。。");

        if ("".equals(myWebView.getUrl()) || null == myWebView.getUrl()) {

            return;
        } else {

            String url = myWebView.getUrl();

            showLog("网页当前Url。。。。。。。。。。。。。。。。。。。。。");

            showLog("分享连接检测" + url);

            for (String s : htmlShare) {

                if (url.contains(s)) {
                    isShareCircle = true;
                }

            }

            showLog("isShareCircle的值为：。。。。。。。。。。。。。。。" + isShareCircle);

            if (isShareCircle) {


            } else {

            }

        }
    }


}
